<?php

use think\migration\Seeder;
use app\common\model\Menu;
use think\facade\Log;

class MenuSeeder extends Seeder
{
    /**
     * Run Method.
     *
     * Write your database seeder using this method.
     *
     * More information on writing seeders is available here:
     * http://docs.phinx.org/en/latest/seeding.html
     */
    public function run()
    {
        $menus = [
            [
                'name' => '首页',
                'jump_url' => '/index',
                'icon_name' => 'dashboard',
            ],
            [
                'name' => '系统设置',
                'jump_url' => '',
                'icon_name' => 'cog',
                'children' => [
                    ['name' => '菜单管理', 'jump_url' => '/menu', 'icon_name' => 'caret-right'],
//                    ['name' => '意见反馈','jump_url'=>'/feedback','icon_name'=>'caret-right'],
//                    ['name' => '配送规则','jump_url'=>'/delivery_rule','icon_name'=>'caret-right'],
                ],
            ],
            [
                'name' => '后台用户管理',
                'jump_url' => '',
                'icon_name' => 'users',
                'children' => [
                    ['name' => '用户管理', 'jump_url' => '/user', 'icon_name' => 'caret-right'],
                    ['name' => '角色管理', 'jump_url' => '/usergroup', 'icon_name' => 'caret-right'],
                ],
            ],
            [
                'name' => '会员管理',
                'jump_url' => '',
                'icon_name' => 'users',
                'children' => [
                    ['name' => '好友关系列表', 'jump_url' => '/relation', 'icon_name' => 'caret-right'],
                    ['name' => '标签', 'jump_url' => '/tag', 'icon_name' => 'caret-right'],
                ],
            ],
        ];
        foreach ($menus as $data) {
           // $this->createMenu($data);
        }
    }

    protected function createMenu($data, $parent = null)
    {
        // 创建一个新的类目对象
        $menu = new Menu(['name' => $data['name'], 'jump_url' => $data['jump_url'], 'icon_name' => $data['icon_name']]);
        // 如果有 children 字段则代表这是一个父类目
        $menu->is_directory = isset($data['children']);
        // 如果有传入 $parent 参数，代表有父类目
        if (!is_null($parent)) {
            $menu->parent()->associate($parent);
        }
        //  保存到数据库
        $menu->save();
        // 如果有 children 字段并且 children 字段是一个数组
        if (isset($data['children']) && is_array($data['children'])) {
            // 遍历 children 字段
            foreach ($data['children'] as $child) {
                // 递归调用 createCategory 方法，第二个参数即为刚刚创建的类目
                $this->createMenu($child, $menu);
            }
        }
    }
}